// pages/direct/direct.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		//当前用户
		user: {},
		obj: {},
		//用户权限
		authority: null,
		//端口
		port: null,
		//设备进场选择时间
		showEnterTime: false,
		//进场时间
		enterStartTime: null,
		enterEndTime: null,
		//开始时间选择框
		showStartTime: false,
		//结束时间选择框
		showEndTime: false,
		//当前时间
		currentStart: new Date().getTime(),
		currentEnd: new Date().getTime(),
		//时间格式
		formatter(type, value) {
			if (type === 'year') {
				return `${value}年`
			} else if (type === 'month') {
				return `${value}月`
			} else if (type === 'day') {
				return `${value}日`
			} else if (type === 'hour') {
				return `${value}时`
			} else if (type === 'minute') {
				return `${value}分`
			} else if (type === 'second') {
				return `${value}秒`
			}
			return value
		},
		//设置上数频率
		showUpCount: false,
		//上数频率值
    input_upCount: null,
    //英文转中文
    EtoC: {
      "set": "设置",
      "OK": "正常",
      "Already in the state of fuel supply to resume, the command is not running!": "已经处于燃油供应恢复状态，指令未运行!",
      "Already in the state of fuel supply cut off, the command is not running!": "已经处于燃油供应切断状态，指令未运行!",
      "Cut off the fuel supply: Success!": "切断燃料供应：成功!",
      "Restore fuel supply: Success!": "恢复燃料供应：成功!",
      "GPS not fixed, Cut off the fuel supply operation delay execution!": "GPS未固定，切断燃油供应操作延迟执行!",
      "Cut off the fuel supply: Delay! GPS not location.": "切断燃油供应：延迟！GPS未定位.",
      "Relay Cut-OFF Successfully!": "断电",
      "Relay Switch-ON Successfully!": "通电",
      "OIL Control Denied! Device not positioned. Execute Later.":"控制被拒绝！设备未定位。稍后执行"
    },
    //停机状态
		shutdownState: null,
		//设备信息
		equipmentInfo: null
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('指令传参');
		console.log(JSON.parse(options.obj));

		this.setData({
			//获取传参
			obj: JSON.parse(options.obj),
			authority: app.globalData.authority,
			user: app.globalData.userInfo
		})

		//判断端口号
    this.commonPort();
    
    //查询设备停机状态
		this.getShutdownState();
		
		//获取设备信息（为了获取设备开停机日志）
		this.getEquipmentInfo();
	},

	//判断端口号
	commonPort() {
		let obj = this.data.obj;
		let portNum = obj.port;
		let localAddress = obj.localAddress;
		let port = '';

		if (portNum == 8888) {
			port = '';
		} else if (portNum == 8880 && localAddress == '47.99.141.227') {
			port = 88800;
		}else if (portNum == 48147) {
			port = 48147;
		} else {
			port = portNum;
		}

		this.setData({
			port: port
		})
	},

	//通电/断电
	onAndOffState({currentTarget}) {
    //当前时间提前5秒
    let startTime1 = new Date().getTime() - 5000;
    let startTime = new Date(startTime1);

    let state=currentTarget.dataset.detail;
    let obj = this.data.obj;  

		if (obj.port == "" || obj.localAddress == "") {
			Toast.fail('设备没有ip和端口信息，请联系管理员');
		} else {
			//判断心跳时间与当前时间比较，是否大于16分钟，如果大于16分钟设备离线，离线走后台更新redis状态
			//如果没有离线直接发送停机/开机指令
			if (obj.ctm != "") {
				let stime = new Date(obj.ctm).getTime();
				let etime = new Date().getTime();
				let usedTime = etime - stime;
				let time = 10 * 60 * 1000;
				if (usedTime > time) {
					//修改设备停机/开机状态
					let param = {
						imei: obj.imei,
						onAndOffState: state
					}
					CommonService.updateEquipmentOffState(param).then(res => {
						if (res.data.data.success) {
							//修改redis开关机状态
              this.updateOnAndOffState(state);

              //查询设备停机状态
							this.getShutdownState();
							
							//开关机日志记录
							this.logCutOff(state);
						}
					})
				} else {
					//未离线，直接发送指令
					if (obj.imei) {
						
						let param2 = {
							imei: obj.imei
						}

						if (state == "on") {
							CommonService.instructSendNo(param2, this.data.port).then(res => {}).catch((
								error) => {}).finally(_ => {                
								this.delayedFunction(startTime, state);

								//开关机日志记录
								this.logCutOff(state);
							});
						}

						if (state == "off") {
							CommonService.instructSendOff(param2, this.data.port).then(res => {}).catch((
								error) => {}).finally(_ => {                
								this.delayedFunction(startTime, state);

								//开关机日志记录
								this.logCutOff(state);
							});
						}
					}
				}
			}
		}
	},

	//修改redis开关机状态
	updateOnAndOffState(state) {
		let obj = this.data.obj;

		let param = {
			imei: obj.imei,
			port: obj.port,
			ip: obj.ip,
			state: state
		}

		CommonService.onAndOffState(param).then(res => { 
      Toast.success({
        duration: 5000,
        message: '设备离线，设备状态已打标记，下次有数据上传会主动发送指令,请留意！'
      });

      setTimeout(() => {
        //刷新设备列表
        this.refreshEquipmentList();
      }, 5000);
		})
	},

	//延迟修改设备状态
	delayedFunction(startTimes, state) {
		let objs = this.data.obj;
    let map = this.jsonToMap(this.data.EtoC);

		Toast.loading({
			duration: 0,
			forbidClick: true,
			message: '发送中...'
		});

		let updateEquipment = {
			imei: objs.imei,
			onAndOffState: state
		}

		setTimeout(() => {
			let endTimes = new Date();
			let startTimeStr = util.timeFormat(startTimes);
			//10秒后
			let endTimeStr = util.timeFormat(endTimes.getTime() + 1000 * 10);

			let data = {
				imei: objs.imei,
				type: 'EQU',
				startTime: startTimeStr,
				endTime: endTimeStr,
			}

			CommonService.findInstructLog(data).then(res => {
				Toast.clear();
				if (res.data.data.result && res.data.data.result.length) {
          let obj = res.data.data.result[0];
          let resStr = obj.analysisdata.result;

					if (
            "Cut off the fuel supply: Success!" == resStr || 
            "Restore fuel supply: Success!" == resStr || 
            "Relay Cut-OFF Successfully!" == resStr || 
            "Relay Switch-ON Successfully!" == resStr ||
            resStr.indexOf('Cut off the fuel supply: Success! Speed:')!=-1
          ) {
						//修改设备停机/开机状态
						CommonService.updateEquipmentOffState(updateEquipment).then(ress => {
							if (ress.data.data.success) {
                //返回的英文提示词改成中文
                let mes = '';
                //带速度的
                if(resStr.indexOf('Cut off the fuel supply: Success! Speed:')!=-1){
                  mes = resStr.replace('Cut off the fuel supply: Success! Speed:','切断燃料供应：成功！速度：')
                }else{
                  //不带速度的直接转换
                  mes = map.get(resStr);
                }
                // wx.showModal({
                //   title: '提示',
                //   content: '这是一个模态弹窗',
                //   showCancel: false, // 不显示取消按钮
                //   success (res) {
                //     if (res.confirm) {
                //       console.log('用户点击确定')
                //     } else if (res.cancel) {
                //       console.log('用户点击取消')
                //     }
                //   }
                // })
                Toast.success({
                  duration: 5000,
                  message: mes
                });
                
							} else {
                Toast.success({
                  duration: 5000,
                  message: '指令发送成功，修改状态失败，请联系管理员'
                });
              }

              //查询设备停机状态
              this.getShutdownState();

              setTimeout(() => {
                //刷新设备列表
                this.refreshEquipmentList();
              }, 5000);
						})

						//已经处于燃油供应切断状态，指令未运行!
					} else if (
						"Already in the state of fuel supply cut off, the command is not running!" == obj.analysisdata.result) {
						let updateEquipmentOff = {
							imei: objs.imei,
							onAndOffState: "off"
						};
						CommonService.updateEquipmentOffState(updateEquipmentOff).then(ress => {
							if (ress.data.data.success) {
                Toast.success({
                  duration: 5000,
                  message: map.get(obj.analysisdata.result)
                });
							} else {
                Toast.success({
                  duration: 5000,
                  message: '指令发送成功，修改状态失败，请联系管理员'
                });
              }

              //查询设备停机状态
              this.getShutdownState();

              setTimeout(() => {
                //刷新设备列表
                this.refreshEquipmentList();
              }, 5000);
						})

						//已经处于燃油供应恢复状态，指令未运行!
					} else if (
						"Already in the state of fuel supply to resume, the command is not running!" ==
						obj.analysisdata.result) {
						let updateEquipmentOn = {
							imei: objs.imei,
							onAndOffState: "on"
						};
						CommonService.updateEquipmentOffState(updateEquipmentOn).then(ress => {
							if (ress.data.data.success) {
                Toast.success({
                  duration: 5000,
                  message: map.get(obj.analysisdata.result)
                });
							} else {
                Toast.success({
                  duration: 5000,
                  message: '指令发送成功，修改状态失败，请联系管理员'
                });
              }

              //查询设备停机状态
              this.getShutdownState();

              setTimeout(() => {
                //刷新设备列表
                this.refreshEquipmentList();
              }, 5000);
						})
					} else {
						let str = map.get(obj.analysisdata.result) == null || map.get(obj
							.analysisdata.result) == "" ? obj.analysisdata.result : map.get(
							obj.analysisdata.result);
            Toast.fail({
              duration: 5000,
              message: str
            });

            //查询设备停机状态
            this.getShutdownState();

            setTimeout(() => {
              //刷新设备列表
              this.refreshEquipmentList();
            }, 5000);
					}

				} else {
          Toast.fail({
            duration: 3000,
            message: '未发送成功，请稍后再试'
          });
        }
			}).catch((error) => {
				Toast.clear();
			})
		}, 5000);
	},

	//设置震动模式
	onSetVibration() {
    let port = this.data.port;
    let imei = this.data.obj.imei;

		let param = {
			imei: imei
    }

    //如果是86875开头的，调上数频率通用接口
    if(imei.indexOf("86812") === -1){
      param.instructContent = 'KWSET,1,ACCM=0#';

      CommonService.generalInstruction(param, port).then(res => {
        Toast.success('操作完成');
      }).catch((error) => {})

    }else{
      CommonService.setVibration(param, port).then(res => {
        Toast.success('操作完成');
      }).catch((error) => {})
    }
	},

	//设置硬件模式
	onRecoveryInit() {
    Toast.loading({
			duration: 0,
			forbidClick: true,
			message: '发送中...'
    });

    let port = this.data.port;
    let imei = this.data.obj.imei;

    let param = {
			imei: imei
    }
    
    //如果是86875开头的，调上数频率通用接口
    if(imei.indexOf("86812") === -1){
      param.instructContent = 'KWSET,1,ACCM=1#';

      CommonService.generalInstruction(param, port).then(res => {
      }).catch((error) => {})

      //延迟调用查询
      this.delayedInstructLog(imei, '设置硬ACC');

    }else{
      CommonService.recoveryInit(param, port).then(res => {
        Toast.success('操作完成');
      }).catch((error) => {})
    }		
	},

	//显示设备进场选择时间
	onShowEnterTime() {
		this.setData({
			showEnterTime: true
		})
	},

	//隐藏设备进场选择时间
	onCloseEnterTime() {
		this.setData({
			showEnterTime: false
		})
	},

	//确定进场
	onEnter() {
		let start = this.data.enterStartTime;
		let end = this.data.enterEndTime;

		if (start && end) {
			if (end >= start) {
				let param = {
					imei: this.data.obj.imei,
					begin: start,
					end: end
				}

				CommonService.deleteIotRunData(param).then(res => {
					Toast.success('操作完成');
				}).catch((error) => {})
			} else {
				Toast.fail('开始日期不能大于结束日期');
			}

		} else {
			Toast.fail('请选择日期');
		}
	},

	//开启外电检测
	onPowerCheck() {
		let port = this.data.port;

		let parameter = {
			imei: this.data.obj.imei
		}

		CommonService.openPowerCheck(parameter, port).then(res => {
			Toast.success('操作完成');
		}).catch((error) => {})
	},

	//打开静止过滤
	onStaticFilterON() {
		let port = this.data.port;

		let parameter = {
			imei: this.data.obj.imei
		}

		CommonService.staticFilterON(parameter, port).then(res => {
			Toast.success('操作完成');
		}).catch((error) => {})
	},

	//关闭静止过滤
	onStaticFilterOFF() {
		let port = this.data.port;

		let parameter = {
			imei: this.data.obj.imei
		}

		CommonService.staticFilterOFF(parameter, port).then(res => {
			Toast.success('操作完成');
		}).catch((error) => {})
	},

	//显示开始时间
	onShowStartTime() {
		this.setData({
			showStartTime: true
		})
	},

	//隐藏开始时间
	onCloseStartTime() {
		this.setData({
			showStartTime: false
		})
	},

	//确认开始时间
	onConfirmStartTime(e) {
		this.setData({
			currentStart: e.detail,
			enterStartTime: util.timeFormatDay(e.detail)
		})
		this.onCloseStartTime();
	},

	//显示结束时间
	onShowEndTime() {
		this.setData({
			showEndTime: true
		})
	},

	//隐藏结束时间
	onCloseEndTime() {
		this.setData({
			showEndTime: false
		})
	},

	//确认结束时间
	onConfirmEndTime(e) {
		this.setData({
			currentEnd: e.detail,
			enterEndTime: util.timeFormatDay(e.detail)
		})
		this.onCloseEndTime();
	},	
  
  //查询设备停机状态
  getShutdownState(){
    let param = {
      imei: this.data.obj.imei,
      selectFields: ['id','imei','onAndOffState']
    }

    CommonService.goFindEquipmentList(param).then(res => {
      this.setData({
        shutdownState: res.data.data.result[0].onAndOffState
      })  
    }).catch((error) => {
    })
  },

  //json数据转成map格式
  jsonToMap(obj) {
    let strMap = new Map();
    for (let k of Object.keys(obj)) {
      strMap.set(k, obj[k]);
    }
    return strMap;
  },

  //刷新设备列表-保证开关机状态一致
  refreshEquipmentList(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 3];
    prevPage.refreshListAndPage();
  },

  //显示设置上数频率
	onShowUpCount() {
		this.setData({
			showUpCount: true
		})
	},

	//隐藏设置上数频率
	onCloseUpCount() {
		this.setData({
			showUpCount: false
		})
	},

	//获取上数频率值
	getUpCountVal(e) {
		this.setData({
			input_upCount: e.detail.value
		})
	},

	//确定上数频率
	onConfirmUpCount() {
    let val = this.data.input_upCount;
    let imei = this.data.obj.imei;

		if (val) {
			val = val.trim();
			//是否是数值
			if (/^(0|[1-9]\d*)(\.\d*)?$/.test(val) && val >= 10) {
				//取整
				val = parseInt(val);
				let port = this.data.port;

				let param = {
					imei: imei,
					instructContent: 'TIMER,' + val + ',' + '600#'
        }
        
        //如果是86875开头的
        if(imei.indexOf("86812") === -1){
          param.instructContent = 'KWSET,1,FREQ=' + val + '#'
        }

        //console.log(param);

				CommonService.generalInstruction(param, port).then(res => {
					Toast.success('操作完成');
					this.onCloseUpCount();
        }).catch((error) => {})
        
			} else {
				Toast.fail('请输入大于10的数字');
			}
		} else {
			Toast.fail('请输入频率值');
		}
  },

  //重启模块
  onRestartModule(){
    Toast.loading({
			duration: 0,
			forbidClick: true,
			message: '发送中...'
    });
    
    let port = this.data.port;
    let imei = this.data.obj.imei;

    let param = {
      imei: imei,
      instructContent: 'RESET#'
    }

    CommonService.generalInstruction(param, port).then(res => {
    }).catch((error) => {
    })

    //当前时间提前5秒
    let startTime1 = new Date().getTime() - 5000;
    let startTime = new Date(startTime1);

    setTimeout(() => {
      let endTimes = new Date();
			let startTimeStr = util.timeFormat(startTime);
			//10秒后
			let endTimeStr = util.timeFormat(endTimes.getTime() + 1000 * 10);

			let data = {
				imei: imei,
				type: 'EQU',
				startTime: startTimeStr,
				endTime: endTimeStr,
      }
            
      CommonService.findInstructLog(data).then(res => {
        if(res.data.data.result && res.data.data.result.length) {
          let obj = res.data.data.result[0];
          let resStr = obj.analysisdata.result;
          if ("RESET=OK" == resStr || "RESET=Success!" == resStr){
            Toast.success('发送成功');
          }else{
            Toast.fail('操作失败');
          }
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
    }, 5000);
  },

  //延迟调用查询指令
  delayedInstructLog(imei, instructName){
    //当前时间提前5秒
    let startTime1 = new Date().getTime() - 5000;
    let startTime = new Date(startTime1);

    setTimeout(() => {
      let endTimes = new Date();
			let startTimeStr = util.timeFormat(startTime);
			//10秒后
			let endTimeStr = util.timeFormat(endTimes.getTime() + 1000 * 10);

			let data = {
				imei: imei,
				type: 'EQU',
				startTime: startTimeStr,
				endTime: endTimeStr,
      }
            
      CommonService.findInstructLog(data).then(res => {
        if(res.data.data.result && res.data.data.result.length) {
          let obj = res.data.data.result[0];
          let resStr = obj.analysisdata.result;

          //不同的指令用不同的表达式
          let expression = false;

          if(instructName=='设置硬ACC'){
            expression = ("SET OK: ACCM=1." == resStr);
          }

          if (expression){
            Toast.success('发送成功');
          }else{
            Toast.fail('发送失败');
          }
        }else{
          Toast.fail('发送失败');
        }
      }).catch((error) => {
        Toast.fail('发送失败');
      })
    }, 5000);
	},
	
	//开关机日志记录
	logCutOff(state){
		let obj = this.data.obj;	
		let info = this.data.equipmentInfo;
		let operateLog = (info.operateLog && info.operateLog.length) ? info.operateLog : [];
		let user = this.data.user;

		operateLog.push({
			equipmentId: obj.equipmentId,
			imei: obj.imei,
			operateUser: user.userName,
			operate: state=='on' ? '开机' : '停机',
			operateTime: util.timeFormat(new Date())
		});

		let param={
      className:'equipment',
      data:{
				id: obj.equipmentId,
				operateLog: operateLog
      }
		}	
		
		CommonService.goSave(param).then(res=>{
			//获取设备信息（取到最新的operateLog）
  		this.getEquipmentInfo();
    }).catch((error) => {
    })
	},

	//获取设备信息
  getEquipmentInfo(){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        id: this.data.obj.equipmentId,
        selectFields:['id','imei','operateLog']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let result=res.data.data.result;
        console.log('设备信息');
				console.log(result[0]);

        this.setData({
          equipmentInfo: result[0]
        })
      }
    }).catch((error) => {
    })
  },

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	}
})